<?php

namespace app\shop\controller;

use app\common\controller\Shop;
use app\common\library\Email;
use think\Controller;


class Business extends Controller
{
    public function __construct()
    {
        parent::__construct(); 

        $this->BusinessModel = model('Business.Business');
        $this->SourceModel = model('Business.Source');
        $this->CouponModel = model('Coupon.Coupon');
        $this->ReceiveModel = model('Coupon.Receive');
        // $this->EmsModel = model('Ems');
        // $this->PayModel = model('pay.Pay');
    }

    //注册接口
    public function register()
    {
        if($this->request->isAjax())
        {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            //先获取客户来源
            $sourceid = $this->SourceModel->where(['name'=>['LIKE', "%家居商城%"]])->value('id');
            
            //生成密码盐
            $salt = randstr();

            //密码进行加密
            $password = md5($password.$salt);
            
            //组装数据
            $data = [
                'mobile' => $mobile,
                'nickname' => build_encrypt($mobile, 3, 4, '*'), //脱敏显示
                'password' => $password,
                'salt' => $salt,
                'gender' => '0',
                'sourceid' => $sourceid,
                'deal' => '0',
                'money' => '0',
                'auth' => '0'
            ];

            //执行插入语句,插入成功会自动返回影响函数
            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if($result === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }else
            {
                $this->success('注册成功', '/business/login');
                exit;
            }
        }
    }

    public function login()
    {
        if($this->request->isAjax())
        {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            //根据手机号码查询用户是否存在
            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if(!$business)
            {
                $this->error('该手机号用户不存在');
                exit;
            }

            if(empty($password))
            {
                $this->error('密码不能为空');
                exit;
            }

            //验证密码
            $salt = $business['salt'];
            $repass = md5($password.$salt);

            //如果加密的密码和数据库的密码要是不一致就说明密码错误
            if($repass != $business['password'])
            {
                $this->error('密码错误');
                exit;
            }

            unset($business['salt']);
            unset($business['password']);
            
            $this->success('登录成功','/business/index', $business);
            exit;
        }
    }

    public function check()
    {
        if($this->request->isAjax())
        {
            $id = $this->request->param('id', 0, 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            if(!$id || empty($mobile)) 
            {
                $this->error('请重新登录', '/business/login');
                exit;
            }

            //根据id和手机号 找出具体人
            $where = ['id'=>$id, 'mobile'=>$mobile];
            $business = $this->BusinessModel->where($where)->find();

            if(!$business)
            {
                $this->error('非法登录', '/business/login');
                exit;
            }

            unset($business['salt']);
            unset($business['password']);

            $this->success('用户存在', null, $business);
            exit;
        }
    }

    public function profile()
    {
        if($this->request->isAjax())
        {
            $id = $this->request->param('id', 0, 'trim');
            $nickname = $this->request->param('nickname', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $gender = $this->request->param('gender', '0', 'trim');
            $code = $this->request->param('code', '', 'trim');

            $business = $this->BusinessModel->find($id);

            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            //组装数据
            $data = [
                'id' => $id,
                'nickname' => $nickname,
                'mobile' => $mobile,
                'email' => $email,
                'gender' => $gender,
            ];

            //判断密码
            if(!empty($password))
            {
                //重新生成密码盐
                $salt = build_ranstr(10);
                $repass = md5($password.$salt);
                $data['salt'] = $salt;
                $data['password'] = $repass;
            }

            //邮箱 判断认证状态
            if($business['email'] != $email)
            {
                $data['auth'] = '0';
            }

            //判断地区
            if(!empty($code))
            {
                $parent = model('Region')->where(['code' => $code])->value('parentpath');

                //将字符串转换为数组
                $list = explode(',', $parent);

                $data['province'] = isset($list[0]) ? $list[0] : null;
                $data['city'] = isset($list[1]) ? $list[1] : null;
                $data['district'] = isset($list[2]) ? $list[2] : null;
            }

            //判断是否有上传图片
            if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0)
            {
                $success = build_upload('avatar');
                if($success['code'])
                {
                    $data['avatar'] = $success['data'];
                }else
                {
                    $this->error($success['msg']);
                    exit;
                }
            }

            //更新
            $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            //更新成功，判断是否有旧图片 如果有就删除
            if(isset($data['avatar']))
            {
                //判断他是否是一个图片，如果是就删除
                @is_file(".".$business['avatar']) && @unlink(".".$business['avatar']);
            }
            
            $this->success('更新成功', '/business/index');
            exit;
        }
    }

    public function email()
    {
        if($this->request->isAjax())
        {
            $id = $this->request->param('id', 0, 'trim');
            $action = $this->request->param('action', '', 'trim');

            $business = $this->BusinessModel->find($id);

            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            if($business['auth'])
            {
                $this->error('您已验证，无须重复验证');
                exit;
            }

            //发送验证码
            if($action == "send")
            {
                $receiver = (isset($business['email']) && !empty($business['email'])) ? trim($business['email']) : '';

                if(empty($receiver))
                {
                    $this->error('邮箱地址为空，请输入邮箱地址');
                    exit;
                }

                //生成验证码
                $code = build_ranstr(5);

                //在插入之前 要把原来旧的验证码要给他删除掉
                //删除、插入、发送动作 保证动作能够一次性完整的执行完毕
                //利用 innodb 当中的 事务操作 就是用来保证动作的一致性

                //开启事务
                $this->EmsModel->startTrans();

                //删除旧的验证码
                $DeleteStatus = $this->EmsModel->where(['email' => $receiver])->delete();

                if($DeleteStatus === FALSE)
                {
                    $this->error('删除过期验证码失败');
                    exit;
                }

                //组装插入邮件验证码表的数据
                $data = [
                    'event' => 'auth',
                    'email' => $receiver,
                    'code' => $code,
                    'times' => 0,
                ];

                //插入验证码
                $AddStatus = $this->EmsModel->save($data);

                if($AddStatus === FALSE)
                {
                    //回滚操作
                    $this->EmsModel->rollback();
                    $this->error('追加验证码失败');
                    exit;
                }

                //发送验证码
                $subject = "邮箱身份验证-".config('site.name');

                $message = "<div>验证码为：<b>$code</b> 有限期：24小时，过期需重新发送</div>";

                $email = new Email;
                
                $result = $email
                    ->to($receiver)
                    ->subject($subject)
                    ->message($message)
                    ->send();

                if($result)
                {
                    //提交事务，让前面执行的动作生效
                    $this->EmsModel->commit();
                    $this->success('发送邮件成功，请注意查收');
                    exit;
                }else
                {
                    //回滚操作
                    $this->EmsModel->rollback();
                    $this->error($email->getError());
                    exit;
                }
            }

            //检测验证码
            if($action == 'check')
            {
                $vercode = $this->request->param('vercode', '', 'trim');

                if(empty($vercode))
                {
                    $this->error('验证码为空');
                    exit;
                }

                //组装条件
                $where = [
                    'email' => $business['email'],
                    'code' => $vercode,
                ];

                $ems = $this->EmsModel->where($where)->find();

                if(!$ems)
                {
                    $this->error('您所输入的验证码不存在');
                    exit;
                }

                //超过了24小时
                if(time() > $ems['createtime'] + 3600 * 24)
                {
                    $this->error('验证码已失效');
                    exit;
                }

                //验证成功的话，就删除验证码 更新 business auth认证字段 1
                // Ems 删除 business 更新 开启事务

                //开启事务
                $this->EmsModel->startTrans();
                $this->BusinessModel->startTrans();

                //删除验证码
                $EmsStatus = $this->EmsModel->destroy($ems['id']);

                if($EmsStatus === FALSE)
                {
                    $this->error('验证码删除失败');
                    exit;
                }

                //更新用户数据
                $data = [
                    'id' => $id,
                    'auth' => '1'
                ];

                //更新用户数据
                $BusinessStatus = $this->BusinessModel->validate('common/Business/Business.auth')->isUpdate(true)->save($data);

                if($BusinessStatus === FALSE)
                {
                    $this->EmsModel->rollback();
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                if($EmsStatus === FALSE || $BusinessStatus === FALSE)
                {
                    $this->BusinessModel->rollback();
                    $this->EmsModel->rollback();
                    $this->error('更新认证失败');
                    exit;
                }else
                {
                    //提交事务，就要从正方向提交
                    $this->EmsModel->commit();
                    $this->BusinessModel->commit();
                    $this->success('更新认证状态成功');
                    exit;
                }
            }

            
        }
    }

    //生成预支付订单
    public function pay()
    {
        if($this->request->isPost())
        {
            $money = $this->request->param('money', '1', 'trim');
            $type = $this->request->param('type', 'zfb', 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            if($money <= 0)
            {
                $this->error('充值的金额不能小于等于0');
                exit;
            }

            if(!in_array($type, ['zfb', 'wx']))
            {
                $this->error('您选择的支付方式有误');
                exit;
            }

            $third = json_encode(['busid' => $busid]);

            //获取域名部分
            $host = Request::instance()->domain();
            $host = trim($host, '/');

            //完整的请求接口地址
            $api = $host."/pay/index/create";

            //异步通知的回调地址
            $callbackurl = $host.'/shop/business/callback';

            // 成功支付后跳转的地址
            $reurl = '/business/pay';

            //微信收款码
            $wxcode = config('site.wxcode') ? config('site.wxcode') : '';
            $wxcode = $host.$wxcode;

            //支付宝收款码
            $zfbcode = config('site.zfbcode');
            $zfbcode = $host.$zfbcode;

            //组装参数
            $data = [
                'name' => 'vue充值',
                'third' => $third,
                'originalprice' => $money,
                'paypage' => '0',  //我们没有用收银台界面 纯粹返回json的结果
                'reurl' => $reurl,
                'callbackurl' => $callbackurl,
                'wxcode' => $wxcode,
                'zfbcode' => $zfbcode,
            ];

            //要看是哪一种支付方式
            if($type == 'wx')
            {
                //微信
                $data['paytype'] = 0;
            }else
            {
                //支付宝
                $data['paytype'] = 1;
            }

            //发起请求
            $result = httpRequest($api, $data);
            
            //有错误
            if(isset($result['code']) && $result['code'] == 0)
            {
                $this->error($result['msg']);
                exit;
            }

            //将json转换为php数组
            $result = json_decode($result, true);

            $this->success('生成支付订单成功', null, $result['data']);
            exit;
        }
    }

    //查询支付订单是否支付完成
    public function query()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $payid = $this->request->param('payid', 0, 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            $pay = $this->PayModel->find($payid);

            if(!$pay)
            {
                $this->error('支付记录不存在');
                exit;
            }

            //获取域名部分
            $host = Request::instance()->domain();
            $host = trim($host, '/');

            //完整的请求接口地址
            $api = $host."/pay/index/status";

            //发起请求
            $result = httpRequest($api, ['payid'=>$payid]);

            //将json转换为php数组
            $result = json_decode($result, true);

            if(isset($result['code']) && $result['code'] == 0)
            {
                $this->error($result['msg']);
                exit;
            }else
            {
                $status = isset($result['data']['status']) ? $result['data']['status'] : 0;
                $this->success('查询充值状态', null, ['status' => $status]);
                exit;
            }
        }
    }

    //充值回调
    public function callback()
    {
        // 判断是否有post请求过来
        if ($this->request->isPost()) 
        {
            // 获取到所有的数据
            $params = $this->request->param();

            // 充值的金额
            // $price = isset($params['price']) ? $params['price'] : 0;
            $price = isset($params['originalprice']) ? $params['originalprice'] : 0;
            $price = floatval($price);

            // 第三方参数(可多参数)
            $third = isset($params['third']) ? $params['third'] : '';

            // json字符串转换数组
            $third = json_decode($third, true);

            // 从数组获取充值的用户id
            $busid = isset($third['busid']) ? $third['busid'] : 0;

            // 支付方式
            $paytype = isset($params['paytype']) ? $params['paytype'] : 0;

            // 支付订单id
            $payid = isset($params['id']) ? $params['id'] : 0;

            $pay = $this->PayModel->find($payid);

            if(!$pay)
            {
                return json(['code' => 0, 'msg' => '支付订单不存在', 'data' => null]);
            }

            $payment = '';

            switch ($paytype) {
                case 0:
                    $payment = '微信支付';
                    break;
                case 1:
                    $payment = '支付宝支付';
                    break;
            }

            //判断充值金额
            if ($price <= 0) 
            {
                return json(['code' => 0, 'msg' => '充值金额为0', 'data' => null]);
            }

            // 加载模型
            $BusinessModel = model('Business.Business');
            $RecordModel = model('Business.Record');

            $business = $BusinessModel->find($busid);

            if (!$business) {
                return json(['code' => 0, 'msg' => '充值用户不存在', 'data' => null]);
            }

            // 开启事务
            $BusinessModel->startTrans();
            $RecordModel->startTrans();

            // 转成浮点类型
            $money = floatval($business['money']);

            // 余额 + 充值的金额
            $updateMoney = bcadd($money,$price,2);

            // 封装用户更新的数据
            $BusinessData = [
                'id' => $business['id'],
                'money' => $updateMoney
            ];

            // 自定义验证器
            $validate = [
                [
                    'money' => ['number','>=:0'],
                ],
                [
                    'money.number' => '余额必须是数字类型',
                    'money.>=' => '余额必须大于等于0元'
                ]
            ];

            $BusinessStatus = $BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

            if($BusinessStatus === false)
            {
                return json(['code' => 0, 'msg' => $BusinessModel->getError(), 'data' => null]);
            }

            // 封装插入消费记录的数据
            $RecordData = [
                'total' => $price,
                'content' => "{$payment}充值了 $price 元",
                'busid' => $business['id']
            ];

            // 插入
            $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);

            if($RecordStatus === false)
            {
                $BusinessModel->rollback();
                return json(['code' => 0, 'msg' => $RecordModel->getError(), 'data' => null]);
            }

            if($BusinessStatus === false || $RecordStatus === false)
            {
                $BusinessModel->rollback();
                $RecordModel->rollback();
                return json(['code' => 0, 'msg' => '充值失败', 'data' => null]);
            }else{
                $BusinessModel->commit();
                $RecordModel->commit();

                // 订单号：\r\n
                // 金额:50元
                // 支付方式：
                // 时间，
                return json(['code' => 1, 'msg' => '充值成功', 'data' => null]);
            }
        }
    }

    //获取优惠券
    public function coupon()
    {
        $busid = $this->request->param('busid', 0, 'trim');

        $business = $this->BusinessModel->find($busid);

        if(!$business)
        {
            $this->error('用户不存在');
            exit;
        }

        //要找出当前这个人所领取的优惠券
        $coupon = $this->ReceiveModel->with(['coupon'])->where(['busid' => $busid, 'receive.status' => '1'])->select();
         
        if($coupon)
        {
            $this->success('返回优惠券', null, $coupon);
            exit;
        }else
        {
            $this->error('无优惠券信息');
            exit;
        }


    }


}
